package com.tedu.egweibo.controller;

import com.tedu.egweibo.common.result.JsonResult;
import com.tedu.egweibo.common.result.StatusCode;
import com.tedu.egweibo.mapper.UserMapper;
import com.tedu.egweibo.pojo.dto.UserRegDTO;
import com.tedu.egweibo.pojo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册功能")
    @PostMapping("/reg")
    public JsonResult insert(@RequestBody @Validated UserRegDTO userRegDTO){
//        if(userRegDTO.getUsername()==null||userRegDTO.getUsername().isEmpty()){
//            throw new RuntimeException("用户名不能为空");
//        }
        //是否重复用户
        User user = userMapper.selectByUsername(userRegDTO.getUsername());
        //已经存在
        if(user != null){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.success();
    };
}
